package com.eascs.mq;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

public class RabbitProducer {
	private static Logger log = LoggerFactory.getLogger(RabbitProducer.class);
	private static final String TASK_QUEUE_NAME = "task_queue";

	public void startMq(String message, String host, String username, String userpass) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost(host);// "172.29.12.201"
			factory.setPort(5672);
			factory.setUsername(username);// "guest"
			factory.setPassword(userpass);// "kaibin"
			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();
			channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
			channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
			log.info("NewTask send :{}", message);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				channel.close();
				connection.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (java.util.concurrent.TimeoutException e) {
			e.printStackTrace();
		}
	}
}
